//
//  ADWebViewController.m
//  JDong
//
//  Created by liunian on 13-12-16.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "ADWebViewController.h"
#import "LocalSubstitutionCache.h"
#import "MBButtonMenuViewController.h"
#import <QuartzCore/QuartzCore.h>

#define kDefaultMenuViewHeight            44
#define kDefaultBottomBarHeight           38
#define kDefaultTopBarHeight              39
#define kDefaultColorHeadHeight           0
#define COLOR_RGB_BOTTOM     [UIColor colorWithRed:234.0/255.0f green:234.0/255.0f blue:234.0/255.0f alpha:1.0]
@interface ADWebViewController ()<UIWebViewDelegate,MFMailComposeViewControllerDelegate,MBButtonMenuViewControllerDelegate>
@property (nonatomic, retain) NSURL *URL;
@property (nonatomic, retain) UIWebView *webView;
@property (nonatomic, retain) UIView    *menuView;
@property (nonatomic, retain) UIButton  *backButton;
@property (nonatomic, retain) UIButton  *backwardButton;
@property (nonatomic, retain) UIButton  *forwardButton;
@property (nonatomic, retain) UIButton  *refreshButton;
@property (nonatomic, retain) NSString  *urlString;
@property (nonatomic, strong) MBButtonMenuViewController *menu;
@end

@implementation ADWebViewController
- (void)dealloc{
    _webView.delegate = nil;
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (id)initWithURL:(NSURL*)pageURL {
    
    if(self = [super init]) {
        self.URL = pageURL;
        LocalSubstitutionCache *urlCache = [[LocalSubstitutionCache alloc] initWithMemoryCapacity:20 * 1024 * 1024
                                                                                     diskCapacity:200 * 1024 * 1024
                                                                                         diskPath:nil
                                                                                        cacheTime:0];
        [LocalSubstitutionCache setSharedURLCache:urlCache];
        [urlCache removeAllCachedResponses];
    }
    
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = COLOR_BG_VIEW;
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000
    
#else
    float systemName = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(systemName >= 7.0)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
        self.view.bounds = CGRectMake(0, -20, self.view.frame.size.width, self.view.frame.size.height);
    }
#endif

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    LocalSubstitutionCache *urlCache = (LocalSubstitutionCache *)[NSURLCache sharedURLCache];
    [urlCache removeAllCachedResponses];
}

- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.menuView];
    [self.webView loadRequest:[NSURLRequest requestWithURL:self.URL]];
}

- (UIWebView *)webView {
    if (!_webView) {
        
        CGFloat  h = [UIScreen mainScreen].bounds.size.height-20;
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame)-h - kDefaultColorHeadHeight,
                                                               self.view.bounds.size.width,
                                                               h - kDefaultBottomBarHeight - kDefaultColorHeadHeight)];
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _webView.scalesPageToFit = YES;
        _webView.delegate = self;
    }
    return _webView;
}

- (UIView *)menuView {
    if (!_menuView) {
        _menuView = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                             self.view.bounds.size.height - kDefaultBottomBarHeight,
                                                             self.view.bounds.size.width,
                                                             kDefaultBottomBarHeight)];
        _menuView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth;
        
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backButton.exclusiveTouch = YES;
        UIImage *image = IMGNAMED(@"btn_back.png");
        _backButton.frame = CGRectMake(10,
                                       floor((_menuView.bounds.size.height-image.size.height)/2),
                                       image.size.width,
                                       image.size.height);
        [_backButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
        self.backButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
        [_menuView addSubview:_backButton];
        
        _backwardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backwardButton.exclusiveTouch = YES;
        image = IMGNAMED(@"btn_web_backward.png");
        _backwardButton.frame = CGRectMake(floor(_menuView.bounds.size.width/2)-40-image.size.width,
                                           floor((_menuView.bounds.size.height-image.size.height)/2),
                                           image.size.width,
                                           image.size.height);
        [_backwardButton addTarget:self action:@selector(backwardButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        _backwardButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleLeftMargin;
        [_menuView addSubview:_backwardButton];
        
        _forwardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _forwardButton.exclusiveTouch = YES;
        image = IMGNAMED(@"btn_web_forward.png");
        _forwardButton.frame = CGRectMake(floor(_menuView.bounds.size.width/2)+10,
                                          floor((_menuView.bounds.size.height-image.size.height)/2),
                                          image.size.width,
                                          image.size.height);
        [_forwardButton addTarget:self action:@selector(forwardButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        _forwardButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleLeftMargin;
        [_menuView addSubview:_forwardButton];
        
        _refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _refreshButton.exclusiveTouch = YES;
        image = IMGNAMED(@"btn_web_refresh.png");
        _refreshButton.frame = CGRectMake(_menuView.bounds.size.width- 2 * (10+image.size.width),
                                          floor((_menuView.bounds.size.height-image.size.height)/2),
                                          image.size.width,
                                          image.size.height);
        [_refreshButton addTarget:self action:@selector(refreshButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        _refreshButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        
        [_menuView addSubview:_refreshButton];
        
        
        UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
        shareButton.exclusiveTouch = YES;
        image = IMGNAMED(@"btn_forward.png");
        shareButton.frame = CGRectMake(self.view.bounds.size.width - 10 - image.size.width,
                                       floor((kDefaultBottomBarHeight-image.size.height)/2),
                                       image.size.width, image.size.height);
        [shareButton addTarget:self
                        action:@selector(share)
              forControlEvents:UIControlEventTouchUpInside];
        shareButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        [_menuView addSubview:shareButton];
        
        _menuView.backgroundColor = COLOR_RGB_BOTTOM;
        [_backButton setBackgroundImage:IMGNAMED(@"btn_dis.png") forState:UIControlStateNormal];
        [_backButton setBackgroundImage:IMGNAMED(@"btn_dis_light.png")
                               forState:UIControlStateHighlighted];
        [_backwardButton setBackgroundImage:IMGNAMED(@"btn_web_backward.png") forState:UIControlStateNormal];
        [_backwardButton setBackgroundImage:IMGNAMED(@"btn_web_backward_light.png")
                                   forState:UIControlStateHighlighted];
        [_forwardButton setBackgroundImage:IMGNAMED(@"btn_web_forward.png") forState:UIControlStateNormal];
        [_forwardButton setBackgroundImage:IMGNAMED(@"btn_web_forward_light.png")
                                  forState:UIControlStateHighlighted];
        [_refreshButton setBackgroundImage:IMGNAMED(@"btn_web_refresh.png") forState:UIControlStateNormal];
        [_refreshButton setBackgroundImage:IMGNAMED(@"btn_web_refresh_light.png")
                                  forState:UIControlStateHighlighted];
        [shareButton setBackgroundImage:IMGNAMED(@"btn_forward.png") forState:UIControlStateNormal];
        [shareButton setBackgroundImage:IMGNAMED(@"btn_forward_light.png") forState:UIControlStateHighlighted];
    }
    return _menuView;
}

#pragma mark - UIWebViewDelegate methods
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    BMLog(@"URL:%@ \n",request.URL);
    NSString* absoluteString = [request.URL absoluteString];
    if ([absoluteString rangeOfString:@"http://item.jd.com/"].length >0) {
        [self HandleJD:absoluteString];
    }
    if ([absoluteString rangeOfString:@"http://www.360buy.com/product/"].length >0) {
        [self Handle360JD:absoluteString];
    }
    return YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    self.forwardButton.enabled = self.webView.canGoForward;
    self.backwardButton.enabled = self.webView.canGoBack;
	self.refreshButton.enabled = YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
	self.forwardButton.enabled = NO;
	self.backwardButton.enabled = NO;
	self.refreshButton.enabled = NO;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"webview fininsh loading %@", [webView.request.URL absoluteString]);
    NSString* absoluteString = [webView.request.URL absoluteString];
    if ([absoluteString rangeOfString:@"http://detail.tmall.com/"].length>0) {
        /////this is a web version url of tmall, need to converse to mobile version url
        //http://a.m.tmall.com/i14568464658.htm
        
        NSArray* substrings = [absoluteString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"?&"]];
        
        
        
        @try {
            NSString* idstring = [substrings objectAtIndex:1];
            NSString* subIdString = [idstring substringFromIndex:3];
            NSString* wapString = [@"" stringByAppendingFormat:@"http://a.m.tmall.com/i%@.htm",subIdString];
            _urlString = wapString;
            NSURL* url = [NSURL URLWithString:[self.urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            if (url)
            {
                NSURLRequest* request = [NSURLRequest requestWithURL:url];
                if (request)
                {
                    [self.webView loadRequest:request];
                }
            }
        }
        @catch (NSException *exception) {
            ///todo
        }
        
    }
    
    
    if ([absoluteString rangeOfString:@"http://item.jd.com/"].length >0) {
        [self HandleJD:absoluteString];
    }
    if ([absoluteString rangeOfString:@"http://www.360buy.com/product/"].length >0) {
        [self Handle360JD:absoluteString];
    }
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    self.forwardButton.enabled = self.webView.canGoForward;
    self.backwardButton.enabled = self.webView.canGoBack;
	self.refreshButton.enabled = YES;
    
    
    
}

-(void)HandleJD:(NSString*)absoluteString
{
    //http://m.jd.com/product/667648.html
    //http://item.jd.com/667648.html
    @try {
        
        NSRange result = [absoluteString rangeOfString:@"http://item.jd.com/"];
        NSString* endString = [absoluteString substringFromIndex:result.location+result.length];
        
        _urlString = [@"http://m.jd.com/product/" stringByAppendingString:endString];
        _urlString = [_urlString stringByAppendingString:@"?v=t"];
        NSURL* url = [NSURL URLWithString:[self.urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        if (url)
        {
            NSURLRequest* request = [NSURLRequest requestWithURL:url];
            if (request)
            {
                [self.webView loadRequest:request];
            }
        }
    }
    @catch (NSException *exception) {
    }
    
    
    
    
}
-(void)Handle360JD:(NSString*)absoluteString
{
    //http://m.jd.com/product/667648.html
    //http://www.360buy.com/product/667648.html
    @try {
        
        NSRange result = [absoluteString rangeOfString:@"http://www.360buy.com/product/"];
        NSString* endString = [absoluteString substringFromIndex:result.location+result.length];
        
        _urlString = [@"http://m.jd.com/product/" stringByAppendingString:endString];
        _urlString = [_urlString stringByAppendingString:@"?v=t"];
        NSURL* url = [NSURL URLWithString:[self.urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        if (url)
        {
            NSURLRequest* request = [NSURLRequest requestWithURL:url];
            if (request)
            {
                [self.webView loadRequest:request];
            }
        }
    }
    @catch (NSException *exception) {
    }
    
    
    
    
}
#pragma mark - UIButton method
- (void)back:(id)sender {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)backwardButtonTapped:(id)sender {
    [self.webView goBack];
}

- (void)forwardButtonTapped:(id)sender {
    [self.webView goForward];
}

- (void)refreshButtonTapped:(id)sender {
    [self.webView reload];
}

#pragma mark - MBButtonMenuViewControllerDelegate
- (void)buttonMenuViewController:(MBButtonMenuViewController *)buttonMenu buttonTappedAtIndex:(NSUInteger)index
{
    [buttonMenu hide];
    switch (index) {
        case 0:
        {
            [[UIApplication sharedApplication] openURL:self.webView.request.URL];
        }
            break;
        case 1:
        {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = self.webView.request.URL.absoluteString;
        }
            break;
        case 2:
        {
            MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
            
            mailViewController.mailComposeDelegate = self;
            [mailViewController setSubject:[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]];
            [mailViewController setMessageBody:self.webView.request.URL.absoluteString isHTML:NO];
            mailViewController.modalPresentationStyle = UIModalPresentationFormSheet;
            
            [self presentViewController:mailViewController animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
    
}

- (void)buttonMenuViewControllerDidCancel:(MBButtonMenuViewController *)buttonMenu{
    [buttonMenu hide];
}
#pragma mark MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error
{
	[self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark action
- (void)back{
    [self.webView goBack];
}
- (void)forward{
    [self.webView goForward];
}
- (void)refresh{
    [self.webView reload];
}
- (void)share{
    [self.menu showInView:self.view];
}
- (void)backParentController{
    [self.navigationController popViewControllerAnimated:YES];
}

- (MBButtonMenuViewController *)menu{
    if (nil == _menu) {
        NSArray *titles = [NSArray arrayWithObjects:@"在Safari中打开",
                           @"拷贝该页网址",
                           @"邮件发送该网址",
                           @"取消", nil];
        _menu = [[MBButtonMenuViewController alloc] init];
        [_menu setButtonTitles:titles];
        [_menu setDelegate:self];
        [_menu setCancelButtonIndex:[[_menu buttonTitles] count]-1];
    }
    return _menu;
}


@end
